package office.action.person;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import office.BusiUtil;
import office.action.person.vo.LeaderInstructionsVo;
import office.action.person.vo.PlanVo;
import office.action.workflow.form.RemindForm;
import office.bo.person.LeaderInstructions;
import office.bo.person.Plan;
import office.bo.person.PlanTemplate;
import office.service.person.IPersonService;
import office.service.workflow.IRemindService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import current.security.user.domain.User;
import current.security.user.manager.service.UserManagerService;
import platform.common.action.BaseAction;
import platform.common.exception.BusinessException;
import platform.util.DateUtil;

@Namespace("/personPlan")
@ParentPackage("struts-base")
@Controller("personPlanAction")
@Scope("prototype")
public class PersonPlanAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	@Resource
	private IPersonService personalServiceImpl;
	private IRemindService remindService;
	private UserManagerService userManagerService;
	private PlanVo planVo;
	private List<Plan> listPlan;
	private List<PlanVo> listNewPlan = new ArrayList<PlanVo>();
	private Integer thisDate = DateUtil.getCurrentDateNoLine();
	private List<User> users = new ArrayList<User>();
	private List<PlanTemplate> planTemplateList ;
	private Map<String,PlanVo> map = new HashMap<String,PlanVo>();
	private Integer planYear;
	private String templateId;
	private String userId;
	private LeaderInstructionsVo leaderInstructionsVo;
	private List<LeaderInstructionsVo> leaderVoList = new ArrayList<LeaderInstructionsVo>();
	
	/**
	 * 保存领导批示
	 * @return
	 */
	@Action(value="saveLeaderInstructions")
	public String saveLeaderInstructions(){
		LeaderInstructions leaderInstructions = new LeaderInstructions();
		leaderInstructions.setContent(leaderInstructionsVo.getContent());
		leaderInstructions.setCreateDate(DateUtil.getDate());
		leaderInstructions.setIsRead(0+"");
		User user = new User();
		user.setId(super.getUserId());
		leaderInstructions.setUser(user);
		Plan plan = new Plan();
		plan.setId(leaderInstructionsVo.getPlanId());
		leaderInstructions.setPlan(plan);
		personalServiceImpl.saveLeaderInstructions(leaderInstructions);
		this.getAjaxMessagesJson().setMessage(true, "", "编辑成功");
		return RESULT_AJAXJSON;
	}
	
	/**
	 * 根据计划ID 查看领导批示。
	 * @return
	 */
	@Action(value="getLeaderInstructionsList",results={@Result(location="/pages/person/plan/leaderInstructionsList.jsp")})
	public String getLeaderInstructionsList(){
		List<LeaderInstructions> thisLeaderInstructionsList = personalServiceImpl.getLeaderInstructionsByPlanId(leaderInstructionsVo.getPlanId());
		for (Iterator<LeaderInstructions> iterator = thisLeaderInstructionsList.iterator(); iterator.hasNext();) {
			LeaderInstructions leaderInstructions = (LeaderInstructions) iterator.next();
			LeaderInstructionsVo leaderInstructionsVo = new LeaderInstructionsVo();
			leaderInstructionsVo.setId(leaderInstructions.getId().toString());
			leaderInstructionsVo.setContent(leaderInstructions.getContent());
			leaderInstructionsVo.setCreateDate(leaderInstructions.getCreateDate());
			leaderInstructionsVo.setIsRead(leaderInstructions.getIsRead());
			leaderInstructionsVo.setUserCname(leaderInstructions.getUser().getCname());
			leaderVoList.add(leaderInstructionsVo);
		}
		return "success";
	}
	/**
	 * 根据计划ID 查看未读的领导批示
	 * @return
	 */
	@Action(value="getNoReadLeaderInstructionsList",results={@Result(location="/pages/person/plan/leaderInstructionsList.jsp")})
	public String getNoReadLeaderInstructionsList(){
		List<LeaderInstructions> thisLeaderInstructionsList = personalServiceImpl.getNoReadLeaderInstructionsList(leaderInstructionsVo.getPlanId(),"0");
		for (Iterator<LeaderInstructions> iterator = thisLeaderInstructionsList.iterator(); iterator.hasNext();) {
			LeaderInstructions leaderInstructions = (LeaderInstructions) iterator.next();
			LeaderInstructionsVo thisLeaderInstructionsVo = new LeaderInstructionsVo();
			thisLeaderInstructionsVo.setId(leaderInstructions.getId().toString());
			thisLeaderInstructionsVo.setContent(leaderInstructions.getContent());
			thisLeaderInstructionsVo.setCreateDate(leaderInstructions.getCreateDate());
			thisLeaderInstructionsVo.setIsRead(leaderInstructions.getIsRead());
			thisLeaderInstructionsVo.setUserCname(leaderInstructions.getUser().getCname());
			leaderVoList.add(thisLeaderInstructionsVo);
			//设置之后，hibernate自动更新到数据库
			if(leaderInstructionsVo.getUserId() != null && leaderInstructionsVo.getUserId().equals(super.getUserId())){
				leaderInstructions.setIsRead("1");
			}
		}
		return "success";
	}
	/**
	 * 根据计划ID 查看本计划详细内容。因为计划展现页面显示不开
	 * @return
	 */
	@Action(value="getPlanById",results={@Result(location="/pages/person/plan/showPlan.jsp")})
	public String getPlanById(){
		try {
			Plan plan = personalServiceImpl.getPlanById(planVo.getId());
			if(plan != null){
				planVo = new PlanVo();
				planVo.setId(plan.getId().toString());
				planVo.setContent(plan.getContent());
				planVo.setTitle(plan.getTitle());
				planVo.setTime(plan.getTime());
				planVo.setFinish(plan.getFinish());
				planVo.setMemo(plan.getMemo());
			}
		} catch (BusinessException e) {
			e.printStackTrace();
		}
		return "success";
	}
	
	/**
	 * 跳转向计划添加页面
	 * @return
	 */
	@Action(value="gotoPlan",results={@Result(location="/pages/person/plan/planAdd.jsp")})
	public String gotoPlan(){
		return "success";
	}
	/**
	 * 保存工作计划。
	 * @return
	 */
	@Action(value="savePlanYear",results={@Result(type="redirect",location="/personPlan/getPlanTemplateByUidAndYear.action?planYear=${planYear}")})
	public String savePlanYear(){
		Plan plan = new Plan();
		try {
			if(planVo != null && planVo.getId() != null && !planVo.getId().equals("")){
				plan = personalServiceImpl.getPlanById(planVo.getId());
				plan.setMemo(planVo.getMemo());
				plan.setFinish(planVo.getFinish());
			}else{
				PlanTemplate planTemplate = new PlanTemplate();
				planTemplate.setId(templateId);
				BeanUtils.copyProperties(plan,planVo);
				plan.setTime(DateUtil.getCurrentDate());
				plan.setPlanTemplate(planTemplate);
				plan.setIsMake("1");
				plan.setIsSend("1");
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		personalServiceImpl.savePersonPlan(plan);
		return "success";
	}
	/**
	 * 开始年度计划
	 * @return
	 * @throws Exception
	 */
	@Action(value="startPlanByYear",results={@Result(type="redirect",location="/personPlan/getPlanTemplateByUidAndYear.action?planYear=${planYear}")})
	public String startPlanByYear() throws Exception{
		planTemplateList = personalServiceImpl.getPlanTemplateByUidAndYear(planYear);
		if(planTemplateList !=null && planTemplateList.size() > 0){
			throw new BusinessException(planYear+"年计划已经启动完成，请勿重复启动年计划！！");
		}
		String[] weeks = { "日", "一", "二", "三", "四", "五", "六" };
		Integer o = 0 ;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
		Calendar c = Calendar.getInstance();
		c.set(planYear, 1, 1, 0, 0);
		c.add(Calendar.DATE,-1);
		c.add(Calendar.MONTH,-1);
		Date beginDate = c.getTime();
		String strYearBeginDate = sdf.format(beginDate);
		System.out.println(strYearBeginDate);
		
		c.add(Calendar.DATE,+1);
		Date endDate = c.getTime();
		String strYearEndDate = sdf.format(endDate);
		PlanTemplate planTemplateYear = new PlanTemplate();
		planTemplateYear.setName(planYear+"");
		planTemplateYear.setCname("年计划");
		planTemplateYear.setMakeYear(planYear);
		planTemplateYear.setBeginDate(Integer.valueOf(strYearBeginDate));
		planTemplateYear.setEndDate(Integer.valueOf(strYearEndDate));
		planTemplateYear.setPlanType("year");
		planTemplateYear.setOrderPro(o++);
		personalServiceImpl.savePlanTemplate(planTemplateYear);
		int quarter = 0;
		int iweek = 0;
		for(int i = 0 ; i < 12; i ++){
			if(i % 3 == 0){
				c.set(planYear, i, 1 , 0 , 0);
				c.add(Calendar.DATE,-1);
				Date beginQuarterDate = c.getTime();
				String strQuarterBeginDate = sdf.format(beginQuarterDate);
				c.add(Calendar.DATE,+1);
				Date endQuerterDate = c.getTime();
				String strQuerterEndDate = sdf.format(endQuerterDate);
				PlanTemplate planTemplateQuarter = new PlanTemplate();
				quarter ++;
				planTemplateQuarter.setName(""+quarter);
				planTemplateQuarter.setCname("季度计划");
				planTemplateQuarter.setMakeYear(planYear);
				planTemplateQuarter.setBeginDate(Integer.valueOf(strQuarterBeginDate));
				planTemplateQuarter.setEndDate(Integer.valueOf(strQuerterEndDate));
				planTemplateQuarter.setPlanType("quarter");
				planTemplateQuarter.setOrderPro(o++);
				personalServiceImpl.savePlanTemplate(planTemplateQuarter);
			}
			
			c.set(planYear, i, 1 ,0 ,0);
			c.add(Calendar.DATE,-1);
			Date beginMonthDate = c.getTime();
			String strMonthBeginDate = sdf.format(beginMonthDate);
			c.add(Calendar.DATE,+1);
			Date endMonthDate = c.getTime();
			String strMonthEndDate = sdf.format(endMonthDate);
			
			PlanTemplate planTemplateMonth = new PlanTemplate();
			planTemplateMonth.setName(""+(i+1));
			planTemplateMonth.setCname("月计划");
			planTemplateMonth.setMakeYear(planYear);
			planTemplateMonth.setBeginDate(Integer.valueOf(strMonthBeginDate));
			planTemplateMonth.setEndDate(Integer.valueOf(strMonthEndDate));
			planTemplateMonth.setPlanType("month");
			planTemplateMonth.setOrderPro(o++);
			personalServiceImpl.savePlanTemplate(planTemplateMonth);
			System.out.println("");
			for(int j = 1 ; j <= DateUtil.getMonthLastDay(planYear,i) ; j ++){
				c.set(planYear, i, j ,9 ,0);
				int week = c.get(Calendar.WEEK_OF_YEAR);//获取是本月的第几周
				int day = c.get(Calendar.DAY_OF_WEEK);//获致是本周的第几天地, 1代表星期天...7代表星期六
				System.out.println(planYear+"-"+i+"-"+j+"今天是本月的第" + week + "周---今天是星期" + weeks[day-1]);
				if(day==Calendar.FRIDAY){
					iweek ++;
					Date beginWeekDate = c.getTime();
					String strWeekBeginDate = sdf.format(beginWeekDate);
					c.set(planYear, i, j ,20 ,0);
					c.add(Calendar.DATE,+1);
					Date endWeekDate = c.getTime();
					String strWeekEndDate = sdf.format(endWeekDate);
					PlanTemplate planTemplateWeek = new PlanTemplate();
					planTemplateWeek.setName(""+iweek);
					planTemplateWeek.setCname("周计划");
					planTemplateWeek.setMakeYear(planYear);
					planTemplateWeek.setBeginDate(Integer.valueOf(strWeekBeginDate));
					planTemplateWeek.setEndDate(Integer.valueOf(strWeekEndDate));
					planTemplateWeek.setPlanType("week");
					planTemplateWeek.setOrderPro(o++);
					personalServiceImpl.savePlanTemplate(planTemplateWeek);
				}
			}
		}
		return "success";
	}
	/**
	 * 根据UID和计划年份获取此人的计划内容。
	 */
	public void getPlanByUidAndYear(){
		if(userId == null || userId.equals("")){
			userId = super.getUserId();
		}
		listPlan = personalServiceImpl.getPlanByUidAndYear(userId, planYear);
		for (Iterator<Plan> iterator = listPlan.iterator(); iterator.hasNext();) {
			Plan plan = (Plan) iterator.next();
			PlanVo pv = new PlanVo();
			try {
				BeanUtils.copyProperties(pv,plan);
				if(pv.getContent() != null && pv.getContent().length() >= 10){
					pv.setContent(plan.getContent().substring(0,9)+"...");
				}
				if(pv.getTitle() != null && pv.getTitle().length() >= 10){
					pv.setTitle(plan.getTitle().substring(0,7)+"...");
				}
				if(pv.getMemo() != null && pv.getMemo().length() >= 10){
					pv.setMemo(plan.getMemo().substring(0,7)+"...");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			map.put(plan.getPlanTemplate().getId(), pv);
		}
	}
	/**
	 * 获取计划模板，根据计划模板和UID信息获取此人的所有工作计划。
	 * @return
	 * @throws BusinessException
	 */
	@Action(value="getPlanTemplateByUidAndYear",results={@Result(location="/pages/person/plan/planContent.jsp")})
	public String getPlanTemplateByUidAndYear() throws BusinessException{
		if(planYear == null || planYear.equals("") ){
			planYear = DateUtil.getYear();
		}
		planTemplateList = personalServiceImpl.getPlanTemplateByUidAndYear(planYear);
		getPlanByUidAndYear();
		getDownUsers();
		if(planTemplateList != null){
			for (Iterator<PlanTemplate> iterator = planTemplateList.iterator(); iterator.hasNext();) {
				PlanTemplate planTemplate = (PlanTemplate) iterator.next();
				PlanVo pv = map.get(planTemplate.getId());
				//如果等于空就验证时间点，进行提示。不为空就是已经建立过工作计划
				if(pv == null){
					pv = new PlanVo();
					pv.setPlanTemplate(planTemplate);
					pv.setIsNull(true);
					if(thisDate >= planTemplate.getBeginDate() && thisDate <= planTemplate.getEndDate()){
						pv.setStatus(1);
					}else if(thisDate>planTemplate.getEndDate()){
						String allRole = BusiUtil.getAllUpLeavel(getUserRoleName());
						List<User> userl = userManagerService.getUserByRoleAndCompany(allRole,getUserCompanyId());
						if(userl != null){
							for (Iterator<User> iterator2 = userl.iterator(); iterator2.hasNext();) {
								User user = (User) iterator2.next();
								RemindForm r = buildRemindFormByPersonPlan(planTemplate.getId(),user.getId(),getUserMap().get("userCname")+" 未按时完成 "+planTemplate.getName()+"-"+planTemplate.getCname()+" 工作计划！");
								remindService.editRemind(r);
							}
						}
						pv.setStatus(2);
					}else if(thisDate < planTemplate.getBeginDate()){
						pv.setStatus(3);
					}
					pv.setThisBeginDate(DateUtil.stringToString(planTemplate.getBeginDate()+""));
					pv.setThisEndDate(DateUtil.stringToString(planTemplate.getEndDate()+""));
				}else{
					//查询领导批示
					List<LeaderInstructions> listLeader = personalServiceImpl.getLeaderInstructionsByPlanId(pv.getId());
					if(listLeader != null){
						pv.setLeaderSize(listLeader.size()+"");
						int i = 0;
						for (Iterator<LeaderInstructions> iterator2 = listLeader.iterator(); iterator2.hasNext();) {
							LeaderInstructions leaderInstructions = (LeaderInstructions) iterator2.next();
							if(leaderInstructions.getIsRead().equals("0")){
								i ++;
							}
						}
						pv.setNoReaderLeaderSize(i+"");
					}
					
				}
				listNewPlan.add(pv);
			}
		}
		return "success";
	}
	/**
	 * 获取下级所有人员，包括本人。
	 */
	public void getDownUsers(){
		if(BusiUtil.validateRole(getUserRoleName())){
			users = userManagerService.getUsersByAllDepartment(getUserDepartmentId());
		}
	}

	public IPersonService getPersonalServiceImpl() {
		return personalServiceImpl;
	}

	public void setPersonalServiceImpl(IPersonService personalServiceImpl) {
		this.personalServiceImpl = personalServiceImpl;
	}

	public PlanVo getPlanVo() {
		return planVo;
	}

	public void setPlanVo(PlanVo planVo) {
		this.planVo = planVo;
	}

	public Integer getPlanYear() {
		return planYear;
	}

	public void setPlanYear(Integer planYear) {
		this.planYear = planYear;
	}

	public List<Plan> getListPlan() {
		return listPlan;
	}

	public void setListPlan(List<Plan> listPlan) {
		this.listPlan = listPlan;
	}

	public List<PlanTemplate> getPlanTemplateList() {
		return planTemplateList;
	}

	public void setPlanTemplateList(List<PlanTemplate> planTemplateList) {
		this.planTemplateList = planTemplateList;
	}

	public Map<String, PlanVo> getMap() {
		return map;
	}

	public void setMap(Map<String, PlanVo> map) {
		this.map = map;
	}

	public Integer getThisDate() {
		return thisDate;
	}

	public void setThisDate(Integer thisDate) {
		this.thisDate = thisDate;
	}

	public List<PlanVo> getListNewPlan() {
		return listNewPlan;
	}

	public void setListNewPlan(List<PlanVo> listNewPlan) {
		this.listNewPlan = listNewPlan;
	}

	public String getTemplateId() {
		return templateId;
	}

	public void setTemplateId(String templateId) {
		this.templateId = templateId;
	}

	public IRemindService getRemindService() {
		return remindService;
	}

	public void setRemindService(IRemindService remindService) {
		this.remindService = remindService;
	}
	
	private RemindForm buildRemindFormByPersonPlan(String id,String userId,String msg){
		RemindForm form=new RemindForm();
		form.setObjId(id);
		form.setObjClassName("PersonPlan");
		form.setName(msg);
		form.setSendDate(new Date());
		form.setRemindUser(userId);
		form.setHandleState(0);
		return form;
	}

	public UserManagerService getUserManagerService() {
		return userManagerService;
	}

	public void setUserManagerService(UserManagerService userManagerService) {
		this.userManagerService = userManagerService;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public LeaderInstructionsVo getLeaderInstructionsVo() {
		return leaderInstructionsVo;
	}

	public void setLeaderInstructionsVo(LeaderInstructionsVo leaderInstructionsVo) {
		this.leaderInstructionsVo = leaderInstructionsVo;
	}

	public List<LeaderInstructionsVo> getLeaderVoList() {
		return leaderVoList;
	}

	public void setLeaderVoList(List<LeaderInstructionsVo> leaderVoList) {
		this.leaderVoList = leaderVoList;
	}


}
